package com.oocl.crmweb.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oocl.crmweb.pojo.Customer;
import com.oocl.crmweb.service.CustomerManager;
import com.oocl.crmweb.service.impl.CustomerManagerFactory;
import com.oocl.crmweb.util.StringUtil;

public class UpdateCustomerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private CustomerManager manager;
	
	public UpdateCustomerServlet() {
		manager = CustomerManagerFactory.getInstance();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String cid = request.getParameter("id");
		
		if (!StringUtil.isInteger(cid)) {
			response.sendRedirect("error?param=id");
			return;
		}
		
		Integer id = Integer.parseInt(cid);
		request.setAttribute("customer", manager.loadCustomer(id));
		request.getRequestDispatcher("update.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// receive parameter
		String cid = request.getParameter("id");
		String cname = request.getParameter("cname");
		String csal = request.getParameter("sal");
		String csex = request.getParameter("sex");
		String cbirth = request.getParameter("birth");
		String[] favs = request.getParameterValues("favs");

		// validate
		if (StringUtil.isNullOrEmpty(cname)) {
			response.sendRedirect("error?param=cname");
			return;
		}
		if (StringUtil.isNullOrEmpty(csal) || !StringUtil.isDouble(csal)) {
			response.sendRedirect("error?param=sal");
			return;
		}
		if (StringUtil.isNullOrEmpty(cbirth)) {
			response.sendRedirect("error?param=birth");
			return;
		}

		// type convert
		Integer id = Integer.parseInt(cid);
		double sal = Double.parseDouble(csal);
		boolean sex = Boolean.parseBoolean(csex);
		Date birth = null;
		try {
			birth = new SimpleDateFormat("yyyy-MM-dd").parse(cbirth);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		// wrap
		Customer c = new Customer(id, cname, sal, sex, birth, favs);

		// call service
		int m = manager.updateCustomer(c);
		if (m > 0) {
			response.sendRedirect("list");
		} else {
			response.sendRedirect("error?param=other");
		}
	}

}
